package top.zhangjianyong.tools.bill.manager.resolver;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.entity.WxBill;
import top.zhangjianyong.tools.factory.WxBillFactory;
import top.zhangjianyong.tools.service.mybatis.IWaBillService;
import top.zhangjianyong.tools.service.mybatis.IWxBillService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WxBillFileResolver extends BaseBillFileResolver<WxBill> implements BillFileResolver<WxBill> {

    @Autowired
    private IWxBillService iWxBillService;

    @Autowired
    public WxBillFileResolver(IWaBillService iWaBillService) {
        super(iWaBillService);
    }

    @Override
    public List<String> clean(List<String> lines) {
        List<String> list = new ArrayList<>();
        boolean flag = false;
        for (int i = 0; i < lines.size(); i++) {
            String s = lines.get(i);
            if (s.startsWith("----------------------微信支付账单明细列表--------------------")) {
                flag = true;
                i++;
            } else if (flag) {
                list.add(s);
            }
        }
        return list;
    }

    @Override
    public void saveBill(WxBill wxBill) {
        iWxBillService.save(wxBill);
    }

    @Override
    public void updateBill(WxBill wxBill) {
        iWxBillService.updateById(wxBill);
    }

    @Override
    public WxBill qryByOrderNo(String orderNo, Long fileId) {
        return iWxBillService.lambdaQuery()
                .eq(WxBill::getOrderNo, orderNo)
                .eq(WxBill::getFileId, fileId)
                .one();
    }

    @Override
    public List<WxBill> createBills(List<String> lines, Long fileId) {
        return lines.stream()
                .map(line -> WxBillFactory.create(line, fileId))
                .collect(Collectors.toList());
    }

    @Override
    public String getPlatform() {
        return "微信";
    }

    @Override
    public boolean canResolver(List<String> lines) {
        if (CollectionUtil.isEmpty(lines)) return false;
        String firstLine = lines.get(0);
        log.info("第一行数据：{}", firstLine);
        return firstLine.contains("微信");
    }

    @Override
    public List<WxBill> getAll() {
        return iWxBillService.listTheLast();
    }

    @Override
    public void afterReadExcel(Long billFileId) {

    }
}
